import drawQrcode from '../../utils/qrcode';
import {
  base64ToSrc
} from './bg.png';
import {
  Draw
} from './canvas';

Page({
  data: {
    dpr: 1
  },
  onLoad() {
    let dpr = wx.getSystemInfoSync().pixelRatio;
    this.setData({
      dpr
    })
    this.drawQrcode()
    // this.drawCenter();
  },
  drawQrcode() {
    const query = wx.createSelectorQuery()

    query.select('#qrcode')
      .fields({
        node: true,
        size: true
      })
      .exec((res) => {
        var canvas = res[0].node

        drawQrcode({
          canvas: canvas,
          width: 310,
          padding: 0,
          background: '#FFFFFF',
          foreground: '#000000',
          text: 'fuck you',
        })

        // 获取临时路径（得到之后，想干嘛就干嘛了）
        wx.canvasToTempFilePath({
          canvasId: 'myQrcode',
          canvas: canvas,
          x: 0,
          y: 0,
          width: 260,
          height: 260,
          destWidth: 260,
          destHeight: 260,
          success: res => {
            this.drawCenter(res.tempFilePath)
          },
          fail(res) {
            wx.showToast({
              title: '二维码生成失败',
              icon: 'none'
            })
          }
        })
      })
  },

  drawCenter(qrcodepath) {
    const {
      dpr
    } = this.data;
    const query = wx.createSelectorQuery()

    query.select('#qrcode-img')
      .fields({
        node: true,
        size: true
      })
      .exec(async (res) => {
        var canvas = res[0].node;
        const ctx = canvas.getContext('2d');
        this.ctx = ctx;
        const width = 689
        const height = 894
        canvas.width = width * dpr
        canvas.height = height * dpr
        const drawer = new Draw(ctx, canvas, true)
        ctx.scale(dpr, dpr)
        // 绘制前清空画布
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        let path = await base64ToSrc();
        await drawer.drawImage(path, {
          left: 0,
          top: 0,
          width,
          height
        }, {
          border: 45
        })
        ctx.save();
        drawer.drawText('120', {
          top: 68,
          left: 0,
          width: 184,
          height: 90
        }, {
          color: '#FF5A11',
          lineHeight: '1.35',
          fontWeight: 'bolder',
          fontSize: 64,
          textAlign: 'right'
        })
        drawer.drawText('元', {
          top: 103,
          left: 189,
          width: 344,
          height: 30
        }, {
          color: '#FF5A11',
          lineHeight: '1',
          fontWeight: 'normal',
          fontSize: 28,
          textAlign: 'left'
        })
        drawer.drawText('时长赠送', {
          top: 149,
          left: 89,
          width: 344,
          height: 30
        }, {
          color: '#060606',
          lineHeight: '1.36em',
          fontWeight: 'normal',
          fontSize: 22,
          textAlign: 'left'
        })
        drawer.drawText(
          "这是一个很寂寞的天，吓着有些伤心的羽", {
            left: 270,
            top: 60,
            width: 344,
            height: 80
          }, {
            color: '#060606',
            lineHeight: '1.38em',
            fontWeight: 'bolder',
            fontSize: 26
          }
        )
        drawer.drawText('有效期: 3天', {
          top: 136,
          left: 270,
          width: 344,
          height: 30
        }, {
          color: '#06060666',
          lineHeight: '1.36em',
          fontWeight: 'normal',
          fontSize: 22
        })
        drawer.drawText('适用门店：长江路安抚安抚', {
          top: 167,
          left: 270,
          width: 344,
          height: 72
        }, {
          color: '#06060666',
          lineHeight: '1.36em',
          fontWeight: 'normal',
          fontSize: 22
        })
        ctx.fillStyle = '#D9D9D9';
        drawer.drawText('卡券码：sd1222323233394', {
          top: 259,
          left: 0,
          width,
          height: 72
        }, {
          color: '#060606',
          lineHeight: '1.36em',
          fontWeight: 'bolder',
          fontSize: 32,
          textAlign: 'center'
        })
        ctx.save();
        drawer.drawImage(qrcodepath, {
          left: 180,
          top: 317,
          width: 309,
          height: 309
        }, {
          border: 2
        })
        ctx.save();
      })
  },
  handleSave() {
    const imgData = this.ctx.canvas.toDataURL('image/png');
    const _that = this;
    wx.getSetting({
      success(res) {
        // 如果已授权
        if (res.authSetting['scope.writePhotosAlbum']) {
          wx.showLoading({
            mask: true
          })
          const fs = wx.getFileSystemManager();
          const number = new Date().getTime();
          const imgFilePath = wx.env.USER_DATA_PATH + '/' + number + '.png'
          fs.writeFile({
            filePath: imgFilePath, //设置下载图片的地址
            data: imgData.slice(22),
            encoding: 'base64',
            success: function (res) {
              wx.saveImageToPhotosAlbum({
                filePath: imgFilePath, //设置下载图片的地址
                success: (res) => {
                  wx.hideLoading()
                  wx.showToast({
                    title: '保存成功',
                  })
                },
                fail: () => {
                  wx.hideLoading()
                  wx.showToast({
                    title: '保存到相册失败',
                  })
                }
              })
            }
          })
          // 如果没有授权 
        } else if (res.authSetting['scope.writePhotosAlbum'] === undefined) {
          // 调起用户授权
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            success() {
              _that.onSaveImage(imgData)
            },
            fail() {
              wx.showToast({
                title: '您没有授权，无法保存到相册',
                icon: 'none'
              })
            }
          })
          // 如果之前授权已拒绝
        } else {
          wx.openSetting({
            success(res) {
              if (res.authSetting['scope.writePhotosAlbum']) {
                _that.onSaveImage(imgData)
              } else {
                wx.showToast({
                  title: '您没有授权，无法保存到相册',
                  icon: 'none'
                })
              }
            }
          })
        }
      }
    })
  }
})